<template>
  <div v-loading="loading" class="train-container">
    <div class="container-top">
      <span class="name">{{ courseData.name }}</span>
      <px-button type="primary" :icon="ArrowLeft" class="goback-btn" @click="goBack">返回</px-button>
    </div>
    <div class="timer flex-center">
      培训时长：<CountDownIcon />
      <span class="count-time" style="display: none">{{ countTime }}</span>
      <span class="count-time">{{ remainingTime }}</span>
    </div>
    <div class="study-content">
      <div v-if="fileType === 'mp4'" class="preview-content">
        <video :src="fileSrc" controls style="width: 100%; height: 100%" />
      </div>
      <div v-else class="preview-content">
        <iframe width="100%" height="100%" name="FILE_PREVIEW" frameborder="0" :src="fileSrc" />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, toRefs, onMounted, onBeforeUnmount, watch } from "vue";
import { useRouter } from "vue-router";
import CountDownIcon from "@/assets/svg/knowledge/countDown.svg?component";
import { getCourseFileAPI, saveProgressAPI, canExamAPI } from "@/api/knowledge/train";
import axios from "axios";
import { getToken } from "@/utils/auth";
import { timeToSeconds, getNow, formateSeconds } from "@/views/all/knowledge/trainManage/utils";
import { PxMessage, PxMessageBox } from "px-ui";
import { ArrowLeft } from "@px-ui/icons-vue";

defineOptions({
  name: "ALL_TRAINMANAGE_MYTRAIN_STUDY"
});

const router = useRouter();

const state = reactive({
  loading: false,
  courseData: {},
  countTime: "00:00:00",
  fileSrc: "",
  fileType: "",
  remainingTime: ""
});
const { loading, courseData, countTime, fileSrc, fileType, remainingTime } = toRefs(state);

onMounted(() => {
  state.courseData = JSON.parse(router.currentRoute.value.query.data);
  state.fileType = state.courseData.docBizName?.split(".")[1];
  getFile();
});

const userInfo = JSON.parse(localStorage.getItem("userInfo"));

// 正计时
watch(
  () => state.countTime,
  val => {
    if (timeToSeconds(val) === state.courseData.period) {
      clearInterval(timer);
      if (state.courseData.examId) {
        PxMessageBox.confirm("培训课程已完成，是否开始考试", "提示", {
          confirmButtonText: "考试",
          cancelButtonText: "返回",
          type: "warning"
        })
          .then(() => {
            saveProgress(true);
            countTimer();
            countRemaining();
            canExam();
          })
          .catch(() => {
            saveProgress(false);
          });
      } else {
        PxMessageBox.confirm("培训课程已完成", "提示", {
          confirmButtonText: "继续学习",
          cancelButtonText: "返回",
          type: "warning"
        })
          .then(() => {
            saveProgress(true);
            countTimer();
            countRemaining();
          })
          .catch(() => {
            saveProgress(false);
          });
      }
    }
  }
);

// 倒计时
let remainTimer;
const countRemaining = () => {
  let t;
  if (state.courseData.progress !== "" || state.courseData.progress !== null) {
    t = Number(state.courseData.period) - Number(state.courseData.progress);
  } else {
    t = Number(state.courseData.period);
  }
  remainTimer = setInterval(() => {
    if (t > 0) {
      t--;
      state.remainingTime = formateSeconds(t);
    } else {
      clearInterval(remainTimer);
    }
  }, 1000);
};

// 保存培训进度
const saveProgress = async isContinue => {
  try {
    state.loading = true;
    const params = {
      id: state.courseData.id,
      trainId: state.courseData.trainId,
      traineeId: state.courseData.traineeId,
      progress: timeToSeconds(state.countTime),
      completeTime: getNow()
    };
    await saveProgressAPI(params);
    // PxMessage.success("保存成功");
    clearInterval(timer);
    if (!isContinue) {
      router.push({
        path: "/all/knowledge/trainManage/myTrain"
      });
    }
  } catch (err) {
    console.log(err);
  } finally {
    state.loading = false;
  }
};

const goBack = () => {
  PxMessageBox.confirm("是否确定返回？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(() => {
      saveProgress();
    })
    .catch(() => {});
};

let timer;
const countTimer = () => {
  let start_time = new Date();
  timer = setInterval(() => {
    let millisecond = new Date() - start_time;
    let h = Math.floor(millisecond / (60 * 60 * 1000));
    h = h < 10 ? "0" + h : h;
    let min = Math.floor((millisecond % (60 * 60 * 1000)) / (60 * 1000));
    min = min < 10 ? "0" + min : min;
    let sec = Math.floor(((millisecond % (60 * 60 * 1000)) % (60 * 1000)) / 1000);
    sec = sec < 10 ? "0" + sec : sec;
    state.countTime = h + ":" + min + ":" + sec;
  }, 1000);
};

const canExam = async () => {
  try {
    state.loading = true;
    const params = {
      trainId: state.courseData.trainId,
      examId: state.courseData.examId,
      traineeId: userInfo.userId
    };
    await canExamAPI(params);
    router.push({
      path: "/all/knowledge/examManage/myExam/exam",
      query: {
        examId: state.courseData.examId,
        examineeId: userInfo.userId
      }
    });
  } catch (error) {
    console.log(error);
    // 跳转到
    router.push({
      path: "/all/knowledge/trainManage/myTrain"
    });
  } finally {
    state.loading = false;
  }
};

const previewVideo = data => {
  state.fileSrc = URL.createObjectURL(new Blob([data]));
};

const previewPPT = data => {
  const blob = new Blob([data], {
    type: "application/pdf;chartset=UTF-8"
  });
  state.fileSrc = URL.createObjectURL(blob);
};

const getFile = async () => {
  // const suffix = state.courseData.docBizName.split(".")[1];
  const nameAry = state.courseData.docBizName?.split(".") || [];
  const type = nameAry[nameAry?.length - 1] || "";
  const suffix = type?.toLowerCase();
  const params = ["pptx", "ppt"].includes(suffix) ? { docBizId: state.courseData.docBizId } : { id: state.courseData.docBizId };
  state.loading = true;
  axios({
    method: "post",
    url: ["pptx", "ppt"].includes(suffix) ? "/ifp/dms/api/v1/training/previewPPTx" : "/ifp/dms/api/v1/doc/preview",
    data: params,
    headers: {
      "Content-Type": "application/json",
      Authorization: "Bearer " + getToken().accessToken || "",
      facCode: localStorage.getItem("facCode") || ""
    },
    responseType: "arraybuffer"
  }).then(async res => {
    if (["mp4"].includes(suffix)) {
      previewVideo(res.data);
    } else if (["pptx", "ppt", "pdf"].includes(suffix)) {
      previewPPT(res.data);
    }
    state.loading = false;
    countTimer();
    countRemaining();
  });
};

onBeforeUnmount(() => {
  clearInterval(timer);
  clearInterval(remainTimer);
});
</script>

<style lang="scss" scoped>
@import url("@/views/all/knowledge/trainManage/scss/common.scss");

.container-top {
  position: relative;
  width: 100%;
  height: 48px;
  line-height: 48px;
  text-align: center;

  .name {
    font-size: 16px;
    font-weight: bold;
  }

  .goback-btn {
    position: absolute;
    top: 0;
    left: 0;
  }
}

.timer {
  display: flex;
  align-items: center;
}

.count-time {
  margin-left: 8px;
  font-size: 24px;
  font-weight: bold;
}

.study-content {
  width: 100%;
  height: calc(100vh - 300px);
  margin-top: 16px;
  border: 1px solid #eee;
  border-radius: 4px;
}

.preview-content {
  width: 100%;
  height: 100%;
}
</style>
